﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using S4Store.Persistent;
using S4Store.Domain;
using LX.Core.Query;
using S4Store.Service.Valid.StoreValid;
using S4Store.Domain.SellerCarBrand;
using S4Store.Domain.CarSales;

namespace S4Store.Service
{
    public class CarSalesService : BaseService
    {

        public IQueryable<MonthCarSale> GetMonthCarSaleQuery()
        {
            return this.GetQuery<MonthCarSale>();
        }
        public IQueryable<MonthCarModelSale> GetMonthCarModelSaleQuery()
        {
            return this.GetQuery<MonthCarModelSale>();
        }

        public MonthCarSale GetMonthCarSale(int year, int month, int day, int storeid, bool getlastmonth = true)
        {
            var monthCarSale = GetMonthCarSaleQuery().FirstOrDefault(t => t.StoreId == storeid && t.Month.Year == year && t.Month.Month == month);
            if (monthCarSale == null)
            {
                monthCarSale = new MonthCarSale();
                monthCarSale.Month = new DateTime(year, month, 1);
            }
            monthCarSale.CurrentDate = new DateTime(year, month, day).MonthLastOrNow();
            monthCarSale.CarModelSales = GetMonthCarModelSaleQuery().Where(t => t.StoreId == storeid && t.Month.Year == year && t.Month.Month == month).ToList();
            foreach (var m in monthCarSale.CarModelSales)
            {
                m.MonthCarSale = monthCarSale;
            }
            return monthCarSale;
        }

        public void ModifyMonthCarSale(MonthCarSale MonthCarSale)
        {
            var oldm = this.GetMonthCarSaleQuery().FirstOrDefault(t => t.Month.Year == MonthCarSale.Month.Year && t.Month.Month == MonthCarSale.Month.Month && t.StoreId == MonthCarSale.StoreId);
            if (oldm != null)
            {
                this.GetSet<MonthCarSale>().Remove(oldm);
            }
            this.GetSet<MonthCarSale>().Add(MonthCarSale);
        }

        public void ModifyMonthCarModelSale(List<MonthCarModelSale> rows)
        {
            if (rows == null || rows.Count() == 0) return;
            foreach (var row in rows)
            {
                if (row.Id != 0)
                {
                    var dbrow = this.GetMonthCarModelSaleQuery().FirstOrDefault(t => t.Id == row.Id);
                    if (dbrow != null)
                    {
                        this.GetSet<MonthCarModelSale>().Remove(dbrow);
                    }
                    row.Id = 0;
                }
                this.GetSet<MonthCarModelSale>().Add(row);
            }
        }
    
    }
}
